package net.sk.china.front.utils;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.druid.util.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.SecureRandom;

/**
 * 验证码工具类
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/6/4 15:55
 * // +----------------------------------------------------------------------
 */

public class ValidateCodeUtil {

    /** 验证码类，用于最后返回此对象，包含验证码图片base64和真值 */
    private static Validate validate = null;
    /**  随机类，用于生成随机参数 */
    private static SecureRandom random = new SecureRandom();
    /**  随机生成字符串的取值范围 */
    private static String randString = "0123456789";

    /** 图片宽度 */
    private static int width = 116;
    /** 图片高度 */
    private static int height = 46;

    /**
     * 将构造函数私有化 禁止new创建
     */
    private ValidateCodeUtil() {
        super();
    }

    /**
     * 获取随机字符
     * @return String
     */
    private static String getRandomChar(int index) {
        //获取指定位置index的字符，并转换成字符串表示形式
        return String.valueOf(randString.charAt(index));
    }

    /**
     * 获得字体
     */
    private static Font getFont() {
        return new Font("Fixedsys", Font.BOLD, 28);
    }

    /**
     * 获得颜色
     * @param frontColor 覆盖颜色
     * @param backColor 背景色
     * @return Color
     */
    private static Color getRandColor(int frontColor, int backColor) {
        int color = 255;
        if(frontColor > color) { frontColor = color; }
        if(backColor > color)  { backColor = color; }
        int red = frontColor + random.nextInt(backColor - frontColor - 16);
        int green = frontColor + random.nextInt(backColor - frontColor -14);
        int blue = frontColor + random.nextInt(backColor - frontColor -18);
        return new Color(red, green, blue);
    }

    /**
     * 绘制字符串,返回绘制的字符串
     * @param graphics 获得BufferedImage对象的Graphics对象
     * @param randomString 随机字符串
     * @param i 坐标倍数
     * @return string
     */
    private static String drawString(Graphics graphics, String randomString, int i) {
        Graphics2D g2d = (Graphics2D) graphics;
        // 设置字体
        g2d.setFont(getFont());
        // 设置颜色
        g2d.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
        String randChar = getRandomChar(random.nextInt(randString.length()));
        // 组装
        randomString += randChar;
        int rot = RandomUtil.randomInt(1, 10);
        g2d.translate(random.nextInt(3), random.nextInt(3));
        g2d.rotate(rot * Math.PI / 180);
        g2d.drawString(randChar, 16*i, 25);
        g2d.rotate(-rot * Math.PI / 180);
        return randomString;
    }

    /**
     * 绘制干扰线
     * @param graphics 获得BufferedImage对象的Graphics对象
     */
    private static void drawLine(Graphics graphics) {
        //起点(x,y)  偏移量x1、y1
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        graphics.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
        graphics.drawLine(x, y, x + xl, y + yl);
    }

    /**
     * 生成Base64图片验证码
     * @return String
     */
    public static Validate getRandomCode() {
        validate = validate == null ? new Validate() : validate;

        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // 获得BufferedImage对象的Graphics对象
        Graphics graphics = image.getGraphics();
        // 填充矩形
        graphics.fillRect(0, 0, width, height);
        // 设置字体
        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 28));
        // 设置颜色
        graphics.setColor(getRandColor(110, 133));
        //绘制干扰线
        int lineSize = 20;
        for(int i = 0; i <= lineSize; i++) {
            drawLine(graphics);
        }
        //绘制字符
        String randomString = "";
        int stringNum = 4;
        for(int i = 1; i <= stringNum; i++) {
            randomString = drawString(graphics, randomString, i);
            validate.setValue(randomString);
        }

        // 释放绘图资源
        graphics.dispose();
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        try {
            // 将绘制得图片输出到流
            ImageIO.write(image, "png", bs);
            String imgSrc = Base64.byteArrayToBase64(bs.toByteArray());
            validate.setBase64Str(imgSrc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return validate;
    }

    /**
     * 验证码类
     */
    public static class Validate implements Serializable {
        private static final long serialVersionUID = 1L;
        private String base64Str;		//Base64 值
        private String value;			//验证码值

        public String getBase64Str() { return base64Str; }
        private void setBase64Str(String base64Str) { this.base64Str = base64Str; }
        public String getValue() { return value; }
        private void setValue(String value) { this.value = value; }
    }

}
